<style lang="less" scoped>
@import "../../style/rolestyle/rolesty.css";
</style>
<template>
  <div class="main">
    <div class="border-list">
      <!-- 查询输入框开始 -->
      <div class="roleInput">
        <span class="roleHint">角色名称:</span
        ><el-input v-model="roleinput" placeholder="角色名称查询"></el-input>
      </div>
      <div class="add-btn">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addVisible = true"
          class="addRoleBtn"
          >添加角色</el-button
        >
      </div>
      <div class="roleSerch">
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="query(roleinput)"
          >查询</el-button
        >
        <el-button type="primary" icon="el-icon-refresh-left">重置</el-button>
      </div>
      <div class="from-list">
        <el-table :data="tableData" border style="width: 100%" class="tab-list">
          <el-table-column align="center" prop="id" label="id" width="80px">
          </el-table-column>
          <el-table-column
            align="center"
            prop="root"
            label="角色名称"
            width="180"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="role_code"
            label="用户代码"
            width="180"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="role_des"
            label="说明"
            width="180"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="role_status"
            label="状态"
            width="100"
          >
            <template slot-scope="scope">
              <span
                class="spn"
                style="margin-left: 10px; background-color: #66b1ff"
                ><a href="javascript:;">{{ scope.row.role_status }}</a></span
              >
            </template>
          </el-table-column>

          <el-table-column align="center" label="Action" width="478">
            　<template slot-scope="scope">
              　　　　　　<el-button
                type="text"
                @click="rootallocation(scope.row.id)"
                >角色菜单</el-button
              >
              　　　　　　<el-button
                type="text"
                @click="modifyUser(scope.row.id)"
                >角色权限</el-button
              >
              　　　　　　<el-button
                type="text"
                @click="seteRolemsg(scope.row.id)"
                >编辑</el-button
              >
              <el-button
                class="delete-btn"
                type="text"
                @click="deleteUser(scope.row.id)"
                ><a href="javascript:;" class="font">删除</a></el-button
              >
              　　　　</template
            >
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage4" -->
        <div class="fenye">
          <div class="block">
            <!-- <el-pagination
              background
               :current-page="queryinfo.pagenum" 
              :page-sizes="[1, 2, 5, 10]"
              :page-size="queryInfo.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination> -->

            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryInfo.pagenum"
              :page-size="queryInfo.pagesize"
              :page-sizes="[1, 2, 5, 10]"
              layout="total, sizes, prev, pager, next ,jumper"
              :total="total"
            >
            </el-pagination>
          </div>
        </div>
        <!-- 添加角色弹窗 -->
        <div class="tianjiauser">
          <el-dialog
            title="添加角色"
            :close-on-click-modal="false"
            :visible.sync="addVisible"
            width="500px"
          >
            <el-form ref="form" :model="form" :rules="rules">
              <el-form-item
                label="角色名称 :"
                :label-width="formLabelWidth"
                placeholder="请输入角色名称"
                prop="root"
                :value="form.root"
              >
                <el-input autocomplete="off" v-model="form.root"></el-input>
              </el-form-item>
              <el-form-item
                label="角色标识 :"
                :label-width="formLabelWidth"
                placeholder="请输入角色标识"
                prop="role_code"
                :value="form.role_code"
              >
                <el-input
                  autocomplete="off"
                  v-model="form.role_code"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="角色备注 :"
                :label-width="formLabelWidth"
                placeholder="请输入角色备注"
                prop="role_des"
                :value="form.role_des"
              >
                <el-input autocomplete="off" v-model="form.role_des"></el-input>
              </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="setAddGroup(form)"
                >确 定</el-button
              >
            </div>
          </el-dialog>
        </div>
        <!-- *********************************************************************** -->
        <!-- 设置角色菜单  弹出框内容 -->
        <div class="setsRole">
          <el-dialog
            title="菜单分配"
            :close-on-click-modal="false"
            :visible.sync="rootvis"
            width="350px"
          >
            <el-form :model="roots" style="overflow-y: scroll; height: 380px">
              <el-tree
                :data="datas"
                show-checkbox
                default-expand-all
                node-key="id"
                ref="tree"
                highlight-current
                :default-checked-keys="defkey"
                :props="defaultProps"
              >
              </el-tree>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="getCheckedNodes"
                >确 定</el-button
              >
            </div>
          </el-dialog>
        </div>
        <!-- 设置角色权限 弹出框内容 -->
        <div class="setsRole">
          <el-dialog
            title="编辑角色用户的权限"
            :visible.sync="Rolepermissions"
            width="50%"
     
            class="setRole"
          >
            <el-transfer v-model="value" :data="data1" @change="handleChange" :titles="titlelist"> </el-transfer>
            <span slot="footer" class="dialog-footer">
              <el-button @click="Rolepermissions = false">取 消</el-button>
              <el-button type="primary" @click="setRoleJurisdiction(data1)"
                >确 定</el-button
              >
            </span>
          </el-dialog>
        </div>
        <!-- 编辑角色    -->
        <div class="ys-Editorialrole">
          <el-dialog
            title="编辑角色"
            :visible.sync="setpwdVisible"
           
            width="500px"
          >
            <el-form ref="form" :model="form" :rules="rules">
              <el-form-item
                :value="form.root"
                prop="root"
                label="角色名称 :"
                :label-width="formLabelWidth"
              >
                <el-input v-model="form.root" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item
                :value="form.role_code"
                prop="role_code"
                label="角色标识 :"
                :label-width="formLabelWidth"
              >
                <el-input
                  v-model="form.role_code"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item
                :value="form.role_des"
                prop="role_des"
                label="角色备注 :"
                :label-width="formLabelWidth"
              >
                <el-input v-model="form.role_des" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="postRoleMsg(form)"
                >确 定</el-button
              >
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  apiGetGroup,
  apiAddGroup,
  apiEditGroup,
  apiQueryGroup,
  apiDeleteGroup,
  apiGetGroupRoutes,
  apiEditRoutes,
  apiSetRoleRoutes,
  apiSetRolejurisdiction
} from "@/api/roleRoot"; // 导入我们的api接口
export default {
  data() {
    const generateData = (_) => {
      const data = [];
      const clientType = ["系统管理员", "省代", "市代"];
      clientType.forEach((client, index) => {
        data.push({
          label: client,
          key: index,
        });
      });

      return data;
    };
    const generateDatas = (_) => {
      const data = [];
      const clientType = ["拒绝后台所有接口"];
      clientType.forEach((client, index) => {
        data.push({
          label: client,
          key: index,
        });
      });

      return data;
    };

    return {
    
      titlelist:["解除","禁用"],
      defaultProps: {
        children: "subitem",
        label: "title",
        label: "name",
      },
      datas: [],
      roots: {
        menus: [],
      },
      id: "",
      rootvis: false,
      defkey: [],
      value: [],
      data: generateData(),
      data1: generateDatas(),
      roleinput: "",
      addVisible: false,
      setpwdVisible: false,
      roleLimitdialogFormVisible: false,
      setRole: false,
      Rolepermissions: false,
      dialogtitle: "添加 管理员",
      formLabelWidth: "90px",
      userList: [],
      form: {
        role_code: "",
        role_des: "",
        root: "",
      },

      rules: {
        root: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        role_code: [
          { required: true, message: "请输入角色标识", trigger: "blur" },
          { message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        role_des: [
          { required: true, message: "请输入角色备注", trigger: "blur" },
        ],
        password: [
          {
            min: 6,
            max: 16,
            required: true,
            message: "请输入6-16位数字或字母",
            trigger: "blur",
          },
        ],
      },
      // 总条数
      total: 0,
      //参数
      queryInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        // 显示一页多少条数据
        pagesize: 1,
      },
      tableData: [],
      setroot: [],
      roleId: "",
      // 穿梭框value值
      transferVal:''
    };
  },
  mounted() {
    this.fenyedianji();
    this.onload();
  },
  methods: {
    //获取全部用户
    onload() {
      apiGetGroup({}).then((res) => {
        this.tableData = res.data;
        this.tableData.forEach((doc) => {
          //更改时间格式
          if (doc.role_status == 1) {
            doc.role_status = this.dayjs(doc.role_status).format("正常");
          } else if(doc.role_status == 2) {
            doc.role_status = this.dayjs(doc.role_status).format("禁用");
          }else{
            doc.role_status = this.dayjs(doc.role_status).format("正常");
          }
        });
      });
    },
    //通过昵称查询用户
    query(val) {
      console.log(val);
      if (!val) {
        this.$message({
          message: "请输入角色名称",
          type: "info",
          duration: 1000,
        });
      } else {
        apiQueryGroup({
          root: val,
        }).then((res) => {
          this.tableData = [];
          this.tableData.push(res.data);
          this.tableData.forEach((doc) => {
            //更改时间格式
            if (doc.role_status == 1) {
              doc.role_status = this.dayjs(doc.role_status).format("正常");
            } else {
              doc.role_status = this.dayjs(doc.role_status).format("禁用");
            }
          });
        });
      }
    },
    // 添加角色
    setAddGroup(form) {
      this.addVisible = false;
      console.log(form);
      let arr = this.filterObj(form);
      if (arr.length == 0) {
        this.$message({
          message: "请输入角色信息",
          type: "info",
          duration: 1000,
        });
      } else {
        apiAddGroup(form).then((res) => {
          console.log(res);
          this.$message({
            message: "添加成功",
            type: "success",
            duration: 1000,
          });
          this.onload();
        });
      }
    },

    // 分页点击
    fenyedianji() {
      this.total = this.tableData.length;
    },
    cancel() {
      // dialog中的表单取消提交
      this.rootvis = false;
      this.addVisible = false;
      this.setpwdVisible = false;
      this.$nextTick(() => {
        if (this.$refs.form !== undefined) {
          this.$refs.form.resetFields();
        }
      });
    },
    //  获取所有角色菜单
    rootallocation(val) {
      this.rootvis = true;
      console.log(val);
      this.roleId = val;
      apiGetGroupRoutes({
        id: val,
      }).then((res) => {
        this.defkey = res.assignedPermissions;
        this.datas = res.systemPermissions.routes;
        console.log(this.defkey);
        console.log(this.$refs.tree.getCheckedKeys());
      });
    },
    // 修改角色菜单
    getCheckedNodes() {
      this.setroot = this.$refs.tree.getCheckedKeys();
      const reg = /^[\u4e00-\u9fa5]+$/;
      console.log(1111);
      const permissions = [];
      this.setroot.forEach((item) => {
        if (!reg.test(item)) {
          permissions.push(item);
        }
      });
      console.log(permissions);
      if (this.roleId == 1) {
        this.$message({
          message: "无法修改管理员菜单",
          type: "info",
          duration: 1000,
        });
      } else {
        apiSetRoleRoutes({
          id: this.roleId,
          permissions: permissions,
        }).then((res) => {
          console.log(res);
        });
      }
    },
    // 设置角色权限
    modifyUser(val) {
      console.log(val);
      this.roleId=val
      if(val==1){
         this.$message({
          message: "无法设置管理员权限",
          type: "info",
          duration: 1000,
        });
      }else{
         this.Rolepermissions = true;
      }
     
    },
      //  穿梭框回调函数
      handleChange(val,direction,movedKeys){
              val=2
         this.transferVal=val 
         if(direction=="right"){
           val=2
           this.transferVal=val
           
         }else if(direction=="left"){
              val=3
                this.transferVal=val 
         }
        console.log(val,direction,movedKeys);
    },  
    // 穿梭框请求
    setRoleJurisdiction( data){
       this.$forceUpdate()
    if(!this.transferVal){
     this.$message({
          message: "请选择是否禁用或解除角色",
          type: "success",
          duration: 1000,
        });
    }else if(this.transferVal==2){
      apiSetRolejurisdiction({
        id:this.roleId,
        keyword:this.transferVal
      }).then(res=>{
        this.$message({
          message: "禁用成功",
          type: "success",
          duration: 1000,
        });      
      })
    }else if(this.transferVal==3){
        apiSetRolejurisdiction({
        id:this.roleId,
        keyword:this.transferVal
      }).then(res=>{
        this.$message({
          message: "解除成功",
          type: "success",
          duration: 1000,
        });
        
      })
    }  
    },
   



    // 编辑角色信息
    seteRolemsg(val) {
      this.roleId = val;
     if(val==1){
        this.$message({
          message: "无法修改管理员信息",
          type: "info",
          duration: 1000,
        });
     }else{
        this.setpwdVisible = true;
     }
    },
    // 编辑角色
    postRoleMsg(val) {
    
      let arr=this.filterObj(val)
      if (this.roleId == 1) {
        this.$message({
          message: "无法修改管理员信息",
          type: "info",
          duration: 1000,
        });
      } else if (arr.length==0) {
        this.$message({
          message: "请输入角色信息",
          type: "info",
          duration: 1000,
        });
      }else{
          apiEditGroup({
            id:this.roleId,
            root:val.root,
            role_code:val.role_code,
            role_des:val.role_des
          }).then(res=>{
            console.log(res);
            this.$message({
          message: "修改成功",
          type: "success",
          duration: 1000,
        });
          })
      }
    },

    //删除角色
    deleteUser(val) {
      if(val==1){
        this.$message({
          message: "无法删除管理员账号",
          type: "info",
          duration: 1000,
        });
      }else{
         apiDeleteGroup({
        id: val,
         }).then((res) => {
            this.$message({
          message: "删除成功",
          type: "success",
          duration: 1000,
        });
         });
         
      }

     
    },
    //关闭时确认弹框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    //  分页
    //监听 pagesize 改变的事件
    handleSizeChange(newsize) {
      //这里conso 选中第几页 最新的值
      console.log(newsize);
      //最新的条数（newsize）赋值给 动态的 pagesie
      this.queryInfo.pagesize = newsize;
      //获取到最新一页显示的数据  重新发送axios请求 这里是封装好的请求方法
      this.userlistinfo();
    },

    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      //把最新的页码（newPage）赋值给 动态的 pagenum
      this.queryInfo.pagenum = newPage;
      //获取到最新显示的页码值  重新发送axios请求 这里是封装好的请求方法
      this.userlistinfo();
    },
    filterObj(val) {
      var arr = Object.values(val).filter(function (item) {
        if (item !== "") {
          return true; //过滤掉为空的项
        }
      });
      return arr;
    },
  },
};
</script>